﻿using SiteGenerator;
using System.Collections.Concurrent;

if (!SiteGeneratorArguments.TryParse(args, out var arguments))
{
    Console.WriteLine(SiteGeneratorArguments.HelpMessage);
    return;
}

if(!arguments.DoOverwriting)
{
    if(arguments.Output.Exists && 
        arguments.Output.EnumerateFiles("*", SearchOption.AllDirectories).Any())
    {
        Console.WriteLine("输出文件夹中存在文件。请选择一个空文件夹，或者在参数中指定需要进行覆盖。");
        return;
    }
}
arguments.Output.Create();

ConcurrentBag<InfoOfLoadedFile> loadedFiles = new ConcurrentBag<InfoOfLoadedFile>();
ConcurrentBag<FileInfo> skippedFiles = new ConcurrentBag<FileInfo>();

var imageDirectory = arguments.Output.CreateSubdirectory("images");
var resizedDirectory = imageDirectory.CreateSubdirectory("resized");

arguments.Input.EnumerateFiles().AsParallel().ForAll(file => {
    Image image;
    try
    {
        Console.WriteLine($"{file.FullName} -> ...");
        image = Image.Load(file.FullName);
    }
    catch (InvalidImageContentException)
    {
        skippedFiles.Add(file);
        return;
    }
    catch (UnknownImageFormatException)
    {
        skippedFiles.Add(file);
        return;
    }

    var outputInfo = new InfoOfLoadedFile(file, imageDirectory, resizedDirectory);
    Console.WriteLine($"{file.FullName} -copy> {outputInfo.Output.FullName} ...");
    file.CopyTo(outputInfo.Output.FullName, true);

    Console.WriteLine($"{file.FullName} -resize> {outputInfo.Resized.FullName} ...");
    image.Mutate(c => {
        var widthFactor = image.Width / arguments.MinWidth;
        var heightFactor = image.Height / arguments.MinHeight;
        var factor = Math.Min(widthFactor, heightFactor);
        if (factor is 0 or 1)
            return;
        c.Resize(image.Width / factor, image.Height / factor);
    });
    image.SaveAsPng(outputInfo.Resized.FullName);
    loadedFiles.Add(outputInfo);
});

using var indexHtml = new StreamWriter(Path.GetFullPath("index.html", arguments.Output.FullName));
indexHtml.WriteLine("""
    <style>
        img {
            width: 10rem;
        }
    </style>

    <div style="flex: auto;">
    """);

foreach (var fileName in loadedFiles.Select(f => f.Input.Name).Order())
{
    indexHtml.WriteLine(
        $"    " +
        $"<a href=\"./images/{fileName}\">" +
        $"<img src=\"./images/resized/{fileName}\">" +
        $"</a>");
}

if (!skippedFiles.IsEmpty)
{
    indexHtml.WriteLine("    <!--");
    foreach (var fileName in skippedFiles.Select(f => f.Name).Order())
    {
        indexHtml.WriteLine(
            $"        " +
            $"<a href=\"./images/{fileName}\">" +
            $"<img src=\"./images/resized/{fileName}\">" +
            $"</a>");
    }
    indexHtml.WriteLine("    -->");
}

indexHtml.WriteLine("</div>");
